﻿<script lang="ts" name="warePlaceModel" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { useWarePlaceModelApi } from '/@/api/interacting/warePlaceModel';
import { getUserList } from '/@/api/customer/userList';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const warePlaceModelApi = useWarePlaceModelApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	userList: [] as any[], // 用户列表
	existingCodes: [] as string[], // 现有编码列表
});

// 自行添加其他规则
const rules = ref<FormRules>({
	warePlaceCode: [{ required: true, message: '请选择库位编码！', trigger: 'blur', },],
	warePlaceName: [{ required: true, message: '请选择库位名称！', trigger: 'blur', },],
	warePlaceVolume: [{ required: true, message: '请选择库位容量！', trigger: 'blur', },],
	warePlaceType: [{ required: true, message: '请选择库位状态！', trigger: 'blur', },],
});

// 页面加载时
onMounted(async () => {
	// 加载用户列表
	try {
		const res = await getUserList();
		console.log('用户列表API响应:', res);
		// 根据API响应结构，数据在result字段中
		let userList = res?.data?.result || res?.result || [];
		
		// 如果用户列表为空，尝试不同的数据结构
		if (userList.length === 0) {
			console.log('尝试其他数据结构...');
			userList = res?.data || res || [];
		}
		
		// 确保value是字符串格式，因为下拉框需要字符串值
		state.userList = userList.map((item: any) => ({
			...item,
			value: String(item.value), // 确保value是字符串
			label: item.label
		}));
		
		console.log('用户列表数据:', state.userList);
		console.log('用户列表长度:', state.userList.length);
	} catch (_error) {
		console.error('加载用户列表失败:', _error);
	}
});

// 生成下一个库位编码
const generateNextCode = () => {
	const prefix = 'WP';
	let maxNumber = 0;
	
	// 从现有编码中找到最大的数字
	state.existingCodes.forEach(code => {
		if (code && code.startsWith(prefix)) {
			const numberPart = code.substring(prefix.length);
			const number = parseInt(numberPart);
			if (!isNaN(number) && number > maxNumber) {
				maxNumber = number;
			}
		}
	});
	
	// 生成下一个编码，确保是三位数字格式
	const nextNumber = maxNumber + 1;
	const paddedNumber = nextNumber.toString().padStart(3, '0');
	const newCode = prefix + paddedNumber;
	
	state.ruleForm.warePlaceCode = newCode;
	ElMessage.success(`已生成编码: ${newCode}`);
};

// 获取现有编码列表
const loadExistingCodes = async () => {
	try {
		// 获取所有库位数据来分析现有编码
		const res = await warePlaceModelApi.page({ page: 1, pageSize: 99999 });
		const items = res?.data?.result?.items || [];
		state.existingCodes = items.map((item: any) => item.warePlaceCode).filter(Boolean);
		console.log('现有编码列表:', state.existingCodes);
	} catch (error) {
		console.error('获取现有编码失败:', error);
		ElMessage.warning('获取现有编码失败，将使用默认编码规则');
		state.existingCodes = [];
	}
};

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {};
	state.ruleForm = row.id ? await warePlaceModelApi.detail(row.id).then(res => res.data.result) : JSON.parse(JSON.stringify(row));
	
	// 如果是新增操作，加载现有编码用于生成新编码
	if (!row.id) {
		await loadExistingCodes();
	}
	
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = state.ruleForm;
			await warePlaceModelApi[state.ruleForm.id ? 'update' : 'add'](values);
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="warePlaceModel-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库位编码" prop="warePlaceCode">
							<el-input v-model="state.ruleForm.warePlaceCode" placeholder="请输入库位编码" maxlength="64"
								show-word-limit clearable>
								<template #append>
									<el-button @click="generateNextCode" type="primary" :icon="'ele-Magic'" 
										title="自动生成编码">生成</el-button>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库位名称" prop="warePlaceName">
							<el-input v-model="state.ruleForm.warePlaceName" placeholder="请输入库位名称" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库位容量" prop="warePlaceVolume">
							<el-input-number v-model="state.ruleForm.warePlaceVolume" placeholder="请输入库位容量" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库位主管" prop="userId">
							<el-select v-model="state.ruleForm.userId" clearable filterable placeholder="请选择库位主管">
								<el-option v-for="user in state.userList" :key="user.value" :label="user.label" :value="user.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库位状态" prop="warePlaceType">
							<el-switch v-model="state.ruleForm.warePlaceType" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库位备注" prop="warePlaceNote">
							<el-input v-model="state.ruleForm.warePlaceNote" placeholder="请输入库位备注" maxlength="512"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>